angular.module('nonghua.controllers.farmer', [])

    .controller('FarmerListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own farmer'),
            add:$rootScope.user_access('add farmer'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:5
        };

        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                town: $scope.addressOption.town,
                village: $scope.addressOption.village,
            };
        };
        $scope.moduleTitle = "农户列表";
        $scope.moduleName = "farmer";
        listCtrl($scope, $rootScope,"farmer_id","farmerList", "farmer_list", $ionicSideMenuDelegate);
    })
    .controller('FarmerDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var listStateName = "farmer-list";
        var resourceName = "farmer_add";
        $scope.listName = "farmerList";
        $scope.moduleTitle = "农户列表";
        $scope.moduleName = "farmer";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own farmer'),
            add:$rootScope.user_access('add farmer'),
        }

        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            init_addr_id:!empty($scope.detail) && !empty($scope.detail.addr_id) ? $scope.detail.addr_id : "",
            level:5
        };
        $scope.distributorOption={
            value:'',
            required:false,
            params:
            {
                action: "get_distributor_all" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'经销商',
            initValue:!empty($scope.detail) && !empty($scope.detail.distributor_id) ? $scope.detail.distributor_id : ''
        };
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                farmer_id: !empty($scope.id) ? $scope.id : "",
                addr_id:_get_address_id($scope.addressOption),
                distributor_id: $scope.distributorOption.value,
                farmer_name: $scope.detail.farmer_name,
                gender: $scope.detail.gender,
                addr_details: $scope.detail.addr_details,
                type: $scope.detail.type,
                phone: $scope.detail.phone,
                cell: $scope.detail.cell,
                email: $scope.detail.email,
                farm_area: _drupalgap_empty_2_zero($scope.detail.farm_area),
                soil_type: $scope.detail.soil_type,
                soil_fertility: $scope.detail.soil_fertility,
                comments: $scope.detail.comments,
            };
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = data.error;
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    .controller('RevisitListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own revisit'),
            add:$rootScope.user_access('add revisit'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:5
        };
        $scope.dateOption={
            year:'',
            month:'',
            day:'',
            level:2
        };
        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                town: $scope.addressOption.town,
                village: $scope.addressOption.village,
                year: $scope.dateOption.year,
                month: $scope.dateOption.month,
            };
        };
        $scope.moduleTitle = "回访记录";
        $scope.moduleName = "revisit";
        listCtrl($scope, $rootScope,"revisit_id","revisitList", "revisit_list", $ionicSideMenuDelegate);
    })
    .controller('RevisitDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory,$ionicSideMenuDelegate) {
        var listStateName = "revisit-list";
        var resourceName = "revisit_add";
        $scope.listName = "revisitList";
        $scope.moduleTitle = "回访记录";
        $scope.moduleName = "revisit";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own revisit'),
            add:$rootScope.user_access('add revisit'),
        }
        chooseFarmerCtrl($scope,$rootScope,$ionicSideMenuDelegate);
        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.visit_date) ? get_year_month_day_from_date($scope.detail.visit_date)['year'] : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.visit_date) ? get_year_month_day_from_date($scope.detail.visit_date)['month'] : '',
            initDay:!empty($scope.detail) && !empty($scope.detail.visit_date) ? get_year_month_day_from_date($scope.detail.visit_date)['day'] : '',
            month:'',
            day:'',
            level:3
        };

        $scope.plantOption={
            value:'',
            params:
            {
                action: "get_plant" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'作物',
            initValue:!empty($scope.detail) && !empty($scope.detail.plant_id) ? $scope.detail.plant_id : ''
        };
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                revisit_id: !empty($scope.id) ? $scope.id : "",
                farmer_id: $scope.farmerInfo.farmer_id,
                plant_id: $scope.plantOption.value,
                visit_date: $scope.dateOption.year+"-"+$scope.dateOption.month+"-"+$scope.dateOption.day,
                unit_yield: $scope.detail.unit_yield,
                net_income: $scope.detail.net_income,
                contrast_yield: $scope.detail.contrast_yield,
                contrast_income: $scope.detail.contrast_income,
                content: $scope.detail.content,
            };
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    .controller('FertilizerCaseListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own fertilizer_case'),
            add:$rootScope.user_access('add fertilizer_case'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:5
        };

        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                town: $scope.addressOption.town,
                village: $scope.addressOption.village,
            };
        };
        $scope.moduleTitle = "施肥案例";
        $scope.moduleName = "fertilizer_case";
        listCtrl($scope, $rootScope,"fertilizer_case_id","fertilizerCaseList", "fertilizer_case_list", $ionicSideMenuDelegate);
    })
    .controller('FertilizerCaseDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory,$ionicSideMenuDelegate,$ionicPopover) {
        var listStateName = "fertilizer-case-list";
        var resourceName = "fertilizer_case_add";
        $scope.listName = "fertilizerCaseList";
        $scope.moduleTitle = "施肥案例";
        $scope.moduleName = "fertilizer_case";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own fertilizer_case'),
            add:$rootScope.user_access('add fertilizer_case'),
        }

        $scope.plantOption={
            value:'',
            params:
            {
                action: "get_plant" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'作物',
            initValue:!empty($scope.detail) && !empty($scope.detail.plant_id) ? $scope.detail.plant_id : ''
        };

        chooseFarmerCtrl($scope,$rootScope,$ionicSideMenuDelegate);
        sub_fertilizer_info($scope,$ionicPopover,'fertilizer_case_extra','fertilizer_case_id');
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                fertilizer_case_id: !empty($scope.id) ? $scope.id : "",
                farmer_id: $scope.farmerInfo.farmer_id,
                plant_id: $scope.plantOption.value,

                effect_desc: $scope.detail.effect_desc,
                real_yield: $scope.detail.real_yield,
            };
            params.subfertilizer=$scope.subFertilizerList;
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    .controller('PlantInfoListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own plant_info'),
            add:$rootScope.user_access('add plant_info'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:5
        };

        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                town: $scope.addressOption.town,
                village: $scope.addressOption.village,
            };
        };
        $scope.moduleTitle = "种植信息";
        $scope.moduleName = "plant_info";
        listCtrl($scope, $rootScope,"plant_info_id","plantInfoList", "plant_info_list", $ionicSideMenuDelegate);
    })
    .controller('PlantInfoDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory,$ionicSideMenuDelegate,$ionicPopover) {
        var listStateName = "plant-info-list";
        var resourceName = "plant_info_add";
        $scope.listName = "plantInfoList";
        $scope.moduleTitle = "种植信息";
        $scope.moduleName = "plant_info";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);

        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own plant_info'),
            add:$rootScope.user_access('add plant_info'),
        }
        chooseFarmerCtrl($scope,$rootScope,$ionicSideMenuDelegate);
        sub_fertilizer_info($scope,$ionicPopover,'fertilization_info','plant_info_id');
        $scope.plantOption={
            value:'',
            params:
            {
                action: "get_plant" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'作物',
            initValue:!empty($scope.detail) && !empty($scope.detail.plant_id) ? $scope.detail.plant_id : ''
        };
        $scope.sowDateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.sow_date) ? get_year_month_day_from_date($scope.detail.sow_date)['year'] : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.sow_date) ? get_year_month_day_from_date($scope.detail.sow_date)['month'] : '',
            initDay:!empty($scope.detail) && !empty($scope.detail.sow_date) ? get_year_month_day_from_date($scope.detail.sow_date)['day'] : '',
            month:'',
            day:'',
            level:3
        };
        $scope.harvestDateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.harvest_date) ? get_year_month_day_from_date($scope.detail.harvest_date)['year'] : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.harvest_date) ? get_year_month_day_from_date($scope.detail.harvest_date)['month'] : '',
            initDay:!empty($scope.detail) && !empty($scope.detail.harvest_date) ? get_year_month_day_from_date($scope.detail.harvest_date)['day'] : '',
            month:'',
            day:'',
            level:3
        };
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                plant_info_id: !empty($scope.id) ? $scope.id : "",

                farmer_id:$scope.farmerInfo.farmer_id,
                plant_id:$scope.plantOption.value,
                sow_date: $scope.sowDateOption.year+"-"+$scope.sowDateOption.month+"-"+$scope.sowDateOption.day,
                harvest_date: $scope.harvestDateOption.year+"-"+$scope.harvestDateOption.month+"-"+$scope.harvestDateOption.day,
                seed: $scope.detail.seed,
                irrigation: $scope.detail.irrigation,
                plant_area: _drupalgap_empty_2_zero($scope.detail.plant_area),
                plant_space: _drupalgap_empty_2_zero($scope.detail.plant_space),
                row_space: _drupalgap_empty_2_zero($scope.detail.row_space),
                general_yield: _drupalgap_empty_2_zero($scope.detail.general_yield),
                other_yield: _drupalgap_empty_2_zero($scope.detail.other_yield),
                seed_cost: _drupalgap_empty_2_zero($scope.detail.seed_cost),
                fertilizer_cost: _drupalgap_empty_2_zero($scope.detail.fertilizer_cost),
                pesticide_cost: _drupalgap_empty_2_zero($scope.detail.pesticide_cost),
                machinery_cost: _drupalgap_empty_2_zero($scope.detail.machinery_cost),
                others_cost: _drupalgap_empty_2_zero($scope.detail.others_cost),
                comments: $scope.detail.comments,
            };
            params.subfertilizer=$scope.subFertilizerList;
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = data.error;
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    .controller('SoilInfoListCtrl', function ($scope, $ionicSideMenuDelegate, $stateParams,$rootScope) {
        $scope.access={
            list:$rootScope.user_access('view own soil_info'),
            add:$rootScope.user_access('add soil_info'),
        }
        $scope.addressOption = {
            province: '',
            city: '',
            county: '',
            town: '',
            village: '',
            level:5
        };

        $scope.updateFilter = function() {
            $scope.filterParams =
            {
                province: $scope.addressOption.province,
                city: $scope.addressOption.city,
                county: $scope.addressOption.county,
                town: $scope.addressOption.town,
                village: $scope.addressOption.village,
            };
        };
        $scope.moduleTitle = "土壤信息";
        $scope.moduleName = "soil_info";
        listCtrl($scope, $rootScope,"soil_info_id","soilInfoList", "soil_info_list", $ionicSideMenuDelegate);
    })
    .controller('SoilInfoDetailCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory,$ionicSideMenuDelegate,$ionicPopover) {
        var listStateName = "soil-info-list";
        var resourceName = "soil_info_add";
        $scope.listName = "soilInfoList";
        $scope.moduleTitle = "土壤信息";
        $scope.moduleName = "soil_info";
        $scope.detailEdit = {editDisabled:false};

        $scope.id = $stateParams.id != "0" ? $stateParams.id : '';
        if(!empty($scope.id)){
            $scope.operation = "修改";
            $scope.detail = $rootScope[$scope.listName][$scope.id];
            $scope.detailEdit.editDisabled = !detailCanEdited($rootScope,$scope);
        }else{
            $scope.operation = "添加";
            $scope.detail={};
        }
        $scope.access={
            list:$rootScope.user_access('view own soil_info'),
            add:$rootScope.user_access('add soil_info'),
        }
        chooseFarmerCtrl($scope,$rootScope,$ionicSideMenuDelegate);
        sub_fertilizer_info($scope,$ionicPopover,'fertilizer_recommendation','soil_info_id');
        $scope.prePlantOption={
            value:'',
            params:
            {
                action: "get_plant" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'前茬作物',
            initValue:!empty($scope.detail) && !empty($scope.detail.pre_plant_id) ? $scope.detail.pre_plant_id : ''
        };
        $scope.recPlantOption={
            value:'',
            params:
            {
                action: "get_plant" //'plant','fertilizer','product','brand','sales_type','department_employee'
            },
            label:'推荐作物',
            initValue:!empty($scope.detail) && !empty($scope.detail.rec_plant_id) ? $scope.detail.rec_plant_id : ''
        };
        $scope.dateOption={
            year:'',
            initYear:!empty($scope.detail) && !empty($scope.detail.sample_date) ? get_year_month_day_from_date($scope.detail.sample_date)['year'] : '',
            initMonth:!empty($scope.detail) && !empty($scope.detail.sample_date) ? get_year_month_day_from_date($scope.detail.sample_date)['month'] : '',
            initDay:!empty($scope.detail) && !empty($scope.detail.sample_date) ? get_year_month_day_from_date($scope.detail.sample_date)['day'] : '',
            month:'',
            day:'',
            level:3
        };
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                soil_info_id: !empty($scope.id) ? $scope.id : "",

                farmer_id:$scope.farmerInfo.farmer_id,
                pre_plant_id:$scope.prePlantOption.value,
                rec_plant_id:$scope.recPlantOption.value,
                sample_date: $scope.dateOption.year+"-"+$scope.dateOption.month+"-"+$scope.dateOption.day,

                title:              $scope.detail.title,
                location:           $scope.detail.location,
                sampler:              $scope.detail.sampler,
                target_yield:               _drupalgap_empty_2_zero($scope.detail.target_yield),
                nitrogen:           _drupalgap_empty_2_zero($scope.detail.nitrogen),
                phosphorus:             _drupalgap_empty_2_zero($scope.detail.phosphorus),
                potassium:             _drupalgap_empty_2_zero($scope.detail.potassium),
                organicmatter:             _drupalgap_empty_2_zero($scope.detail.organicmatter),
                ph:                         _drupalgap_empty_2_zero($scope.detail.ph),
                calcium:             _drupalgap_empty_2_zero($scope.detail.calcium),
                magnesium:             _drupalgap_empty_2_zero($scope.detail.magnesium),
                sulfur:             _drupalgap_empty_2_zero($scope.detail.sulfur),
                zinc:             _drupalgap_empty_2_zero($scope.detail.zinc),
                copper:             _drupalgap_empty_2_zero($scope.detail.copper),
                iron:             _drupalgap_empty_2_zero($scope.detail.iron),
                boron:             _drupalgap_empty_2_zero($scope.detail.boron),
                manganese:             _drupalgap_empty_2_zero($scope.detail.manganese),
            };
            params.subfertilizer=$scope.subFertilizerList;
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $ionicLoading.hide();
                    if (data.option) {
                        $ionicHistory.clearCache().then(function(){ $state.go(listStateName);});
                        alert("操作成功！");
                    } else {
                        var msg = ""
                        if(data.errorNum == 3){
                            msg = "无权限！"
                        }
                        alert("操作失败！"+msg);
                    }
                },
                error: function (xhr, status, message) {
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })
    .controller('GenuineVerificationCtrl', function ($scope,$stateParams,$rootScope,$ionicLoading,$state,$ionicHistory) {
        var resourceName = "genuine_verification_list";
        $scope.moduleTitle = "正品验证";
        $scope.moduleName = "genuine_verification";
        $scope.GenuineVerificationList = [];
        $scope.result=true;
        $scope.detail = {};
        $scope.submitForm = function (form) {
            var path_to_source = 'mobile_service_resources/'+resourceName;
            var params = {
                code:$scope.detail.code,
            };
            console.log(params);
            $ionicLoading.show({
                content: '请稍后',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 200,
                showDelay: 0
            });
            _get_datasouce_result({
                path: path_to_source,
                param: params,
                resource: resourceName,
                success: function (data) {
                    $scope.GenuineVerificationList = [];
                    var length = data.data.length;
                    if (data.data && data.data.length > 0) {
                        console.log(data);
                        $scope.result=true;
                        for(var i = 0;i<length;i++){
                            $scope.GenuineVerificationList.push(data.data[i]);
                        }
                    }else{
                        $scope.result=false;
                    }
                    $ionicLoading.hide();
                    $scope.$apply();
                },
                error: function (xhr, status, message) {
                    $scope.GenuineVerificationList = [];
                    $ionicLoading.hide();
                    $state.go('error');
                }
            });
        }
    })